package com.echo.register.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.echo.register.client.hosp.HospitalFeignClient;
import com.echo.register.client.user.UserFeignClient;
import com.echo.register.common.constant.MqConst;
import com.echo.register.common.exception.RegisterException;
import com.echo.register.common.helper.HttpRequestHelper;
import com.echo.register.common.result.ResultCodeEnum;
import com.echo.register.common.service.RabbitService;
import com.echo.register.enums.OrderStatusEnum;
import com.echo.register.model.order.OrderInfo;
import com.echo.register.model.user.Patient;
import com.echo.register.order.mapper.OrderInfoMapper;
import com.echo.register.order.service.OrderService;
import com.echo.register.order.service.WeixinService;
import com.echo.register.vo.hosp.ScheduleOrderVo;
import com.echo.register.vo.msm.MsmVo;
import com.echo.register.vo.order.*;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: OrderServiceImpl
 * @Package: com.echo.register.order.service.impl
 * @Description:
 * @Author 谢同学
 * @Create 2024/1/4 21:22
 * @Version 1.0
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class) //事务回滚 只要发生异常就回滚
public class OrderServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderService {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private WeixinService weixinService;

    /**
     * 保存订单 & 对接医院系统
     *
     * @param scheduleId 排班id
     * @param patientId  就诊人id
     * @return 订单id
     */
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        // 调用户服务查询就诊人信息
        Patient patientOrder = userFeignClient.getPatientOrder(patientId);

        // 调医院服务获取下单排班信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        // 判断当前时间是否处于可预约时间
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow() || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new RegisterException(ResultCodeEnum.TIME_NO);
        }
        // 保存信息
        OrderInfo orderInfo = new OrderInfo();
        // 封装信息
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        orderInfo.setOutTradeNo(System.currentTimeMillis() + "" + new Random().nextInt(100));// 生成订单号(系统毫秒值+100以内的随机数)
        // 就诊人信息
        orderInfo.setUserId(patientOrder.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patientOrder.getName());
        orderInfo.setPatientPhone(patientOrder.getPhone());
        // 订单状态 0,"预约成功，待支付"
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        // 插入数据库
        baseMapper.insert(orderInfo);
        log.info("【订单服务-保存订单】：{}", JSONObject.toJSONString(orderInfo));
        // 调医院服务获取签名信息
        SignInfoVo singKeyOrder = hospitalFeignClient.getSingKeyOrder(scheduleOrderVo.getHoscode());
        if (singKeyOrder == null) {
            throw new RegisterException(ResultCodeEnum.PARAM_ERROR);
        }
        // 组装参数
        Map<String, Object> paramMap = new HashMap<>(); // 用于最终数据的封装
        // 排班信息
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getHosScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());
        // 就诊人
        paramMap.put("name", patientOrder.getName());
        paramMap.put("certificatesType", patientOrder.getCertificatesType());
        paramMap.put("certificatesNo", patientOrder.getCertificatesNo());
        paramMap.put("sex", patientOrder.getSex());
        paramMap.put("birthdate", patientOrder.getBirthdate());
        paramMap.put("phone", patientOrder.getPhone());
        paramMap.put("isMarry", patientOrder.getIsMarry());
        paramMap.put("provinceCode", patientOrder.getProvinceCode());
        paramMap.put("cityCode", patientOrder.getCityCode());
        paramMap.put("districtCode", patientOrder.getDistrictCode());
        paramMap.put("address", patientOrder.getAddress());
        paramMap.put("isInsure", patientOrder.getIsInsure());
        //联系人
        paramMap.put("contactsName", patientOrder.getContactsName());
        paramMap.put("contactsCertificatesType", patientOrder.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patientOrder.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patientOrder.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());// 时间戳
        paramMap.put("sign", HttpRequestHelper.getSign(paramMap, singKeyOrder.getSignKey()));// 签名
        // 调医院系统挂号接口下订单
        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, singKeyOrder.getApiUrl() + "/order/submitOrder");
        // 判断是否发送成功
        if (jsonObject.getInteger("code") == 200) {
            // 成功

            // 接收医院返回的数据,更新订单
            JSONObject data = jsonObject.getJSONObject("data");
            orderInfo.setHosRecordId(data.getString("hosRecordId"));//预约记录唯一标识
            orderInfo.setNumber(data.getInteger("number"));//预约序号
            orderInfo.setFetchTime(data.getString("fetchTime"));//取号时间
            orderInfo.setFetchAddress(data.getString("fetchAddress"));//取号地址
            // 更新数据库信息
            baseMapper.updateById(orderInfo);
            log.info("【订单服务-更新订单】：{}", JSONObject.toJSONString(orderInfo));
            // 更新号源 & 发送短信通知
            Integer reservedNumber = data.getInteger("reservedNumber");//排班可预约数
            Integer availableNumber = data.getInteger("availableNumber");// 排班剩余预约数
            // 组装消息体
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setAvailableNumber(availableNumber);
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            // 组装短信实体
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + " " + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> map = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(map);
            orderMqVo.setMsmVo(msmVo);
            // 发送mq消息
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            log.info("【订单服务-发送更新号源消息】：{}", JSONObject.toJSONString(orderMqVo));
        } else {
            // 失败
            throw new RegisterException(jsonObject.getString("message"), jsonObject.getInteger("code"));
        }
        return orderInfo.getId();
    }

    /**
     * 订单列表
     * @param pageParam    分页参数
     * @param orderQueryVo 查询条件
     * @return 订单
     */
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<OrderInfo>()
                .like(!StringUtils.isEmpty(orderQueryVo.getUserId()), OrderInfo::getUserId, orderQueryVo.getUserId()) // 用户id
                .like(!StringUtils.isEmpty(orderQueryVo.getKeyword()), OrderInfo::getHosname, orderQueryVo.getKeyword()) // 医院名称
                .eq(!StringUtils.isEmpty(orderQueryVo.getPatientId()), OrderInfo::getPatientId, orderQueryVo.getPatientId()) //就诊人id
                .eq(!StringUtils.isEmpty(orderQueryVo.getOrderStatus()), OrderInfo::getOrderStatus, orderQueryVo.getOrderStatus()) //订单状态
                .like(!StringUtils.isEmpty(orderQueryVo.getPatientName()), OrderInfo::getPatientName, orderQueryVo.getPatientName()) //就诊人姓名
                .ge(!StringUtils.isEmpty(orderQueryVo.getReserveDate()), OrderInfo::getReserveDate, orderQueryVo.getReserveDate()) //安排时间
                .ge(!StringUtils.isEmpty(orderQueryVo.getCreateTimeBegin()), OrderInfo::getCreateTime, orderQueryVo.getCreateTimeBegin()) //创建时间
                .le(!StringUtils.isEmpty(orderQueryVo.getCreateTimeEnd()), OrderInfo::getCreateTime, orderQueryVo.getCreateTimeEnd());//创建时间

        Page<OrderInfo> orderInfoPage = baseMapper.selectPage(pageParam, wrapper);
        orderInfoPage.getRecords().forEach(this::packOrderInfo);
        return orderInfoPage;
    }

    /**
     * 根据订单id查询订单详情
     *
     * @param orderId 用户id
     * @return 订单详情
     */
    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        packOrderInfo(orderInfo);
        return orderInfo;
    }

    /**
     * 订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, Object> show(Long orderId) {
        Map<String, Object> map = new HashMap<>();
        OrderInfo orderInfo = this.getOrderInfo(orderId);
        this.packOrderInfo(orderInfo);
        map.put("orderInfo", orderInfo);
        // 获取就诊人信息
        Patient patient = userFeignClient.getPatientOrder(orderInfo.getPatientId());
        map.put("patient", patient);
        return map;
    }

    /**
     * 取消预约
     *
     * @param orderId 订单id
     * @return 是否取消成功
     */
    @Override
    public Boolean cancelOrder(Long orderId) {
        // 1、查询订单
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if (orderInfo == null) {
            throw new RegisterException(ResultCodeEnum.PARAM_ERROR);
        }
        // 2、

        // 获取退号时间 并判断当前时间 是否能够退号
        if (new DateTime().isAfter(new DateTime(orderInfo.getQuitTime()))) {
            throw new RegisterException(ResultCodeEnum.CANCEL_ORDER_NO);
        }
        // 3、获取签名信息
        SignInfoVo singKeyOrder = hospitalFeignClient.getSingKeyOrder(orderInfo.getHoscode());
        if (singKeyOrder == null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }


        // 4、对接医院系统取消订单
        // 组装参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("hoscode", orderInfo.getHoscode());
        map.put("hosRecordId", orderInfo.getHosRecordId());
        map.put("timestamp", HttpRequestHelper.getTimestamp());
        map.put("sign", HttpRequestHelper.getSign(map, singKeyOrder.getSignKey()));
        // 发送请求
        JSONObject jsonObject = HttpRequestHelper.sendRequest(map, singKeyOrder.getApiUrl() + "/order/updateCancelStatus");
        log.info("【订单服务-调医院系统取消订单】：{}", JSONObject.toJSONString(jsonObject));
        if (jsonObject.getInteger("code") != 200) {
            // 请求失败
            throw new RegisterException(jsonObject.getString("message"), jsonObject.getInteger("code"));
        } else {


            // 5、 判断是否已支付，调用微信退款接口退款
            if (Objects.equals(orderInfo.getOrderStatus(), OrderStatusEnum.PAID.getStatus())) {
                if (!weixinService.refund(orderId)) {
                    throw new RegisterException("微信退款失败", ResultCodeEnum.FAIL.getCode());
                }
            }


            // 6、更新订单信息
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus()); // 取消预约
            baseMapper.updateById(orderInfo);


            // 7、更新号源&发送短信
            // 组装消息
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getHosScheduleId());// 医院系统的排班主键
            // orderMqVo.setAvailableNumber(); 将来接收方将剩余预约数+1 即可
            // 短信实体
            MsmVo msmVo = new MsmVo();
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            // 消息体
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            // msmVo.getTemplateCode() // 当前使用的是测试模板
            msmVo.setParam(param);
            msmVo.setPhone(orderInfo.getPatientPhone());
            orderMqVo.setMsmVo(msmVo);
            // 发送消息给医院服务 更新号源
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            log.info("【订单服务-发送更新号源消息】：{}", JSONObject.toJSONString(orderMqVo));
            return true;
        }

    }

    /**
     * 就诊提醒
     */
    @Override
    public void patientTips() {
        log.info("【订单服务-接收定时消息】。。。");
        // 获取当天就诊人的订单
        List<OrderInfo> orderInfos = baseMapper.selectList(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getReserveDate, new Date()));
        if (orderInfos != null) {
            orderInfos.forEach(orderInfo -> {
                // 短信内容
                String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
                Map<String, Object> param = new HashMap<String, Object>() {{
                    put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                }};
                // 短信实体
                MsmVo msmVo = new MsmVo();
                msmVo.setPhone(orderInfo.getPatientPhone());// 就诊人手机号
                msmVo.setParam(param);

                // 发MQ消息，由短信服务消费发送短信提醒
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
                log.info("【订单服务-发送定时消息提醒就诊人就诊】:{}",msmVo);
            });
        }
    }

    /**
     * 获取医院每天平台预约数量
     *
     * @param orderCountQueryVo 查询条件
     * @return 时间  每天数量
     */
    @Override
    public Map<String, Object> getOrderCountMap(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> orderCountList = baseMapper.getOrderCountList(orderCountQueryVo);
        Map<String,Object> resultMap =new HashMap<>();
        if (orderCountList != null) {
            // 处理日期列表
            List<String> dateList = orderCountList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
            // 处理数量列表
            List<Integer> countList = orderCountList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
            resultMap.put("dateList",dateList);
            resultMap.put("countList",countList);
        }
        return  resultMap;
    }

    /**
     * 订单状态封装
     *
     * @param orderInfo 订单信息
     */
    private void packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
    }
}
